# —*— coding: utf-8 -*-

from timeit import timeit

import asyncio
import random

import logging
import py_global


logger = logging.getLogger(__name__)


async def task(i):
    logger.info('sleep %d' % i)
    await asyncio.sleep(i)


async def func(event_loop):
    task_list = [event_loop.create_task(task(i)) for i in range(1, 5)]
    await asyncio.wait(task_list)


def main():
    event_loop = asyncio.get_event_loop()
    event_loop.run_until_complete(func(event_loop))
    event_loop.close()
    pass


async def async_def_name(delay: float, text: str):
    await asyncio.sleep(delay)
    logger.info('coroutine_name:' + text)
    pass


async def async_def_main():
    logger.info('start')
    coroutine0 = async_def_name(2, 'world')
    coroutine1 = async_def_name(1, 'hello')

    await coroutine0
    await coroutine1
    logger.info('end')

    pass


async def async_def_task():
    task0 = asyncio.create_task(async_def_name(2, 'world'))
    task1 = asyncio.create_task(async_def_name(1, 'hello'))

    logger.info('start')
    await task0
    await task1
    logger.info('end')

    pass


def asyncio_py36():
    """Python 3.6+"""

    coroutine0 = async_def_name(2, 'world')
    coroutine1 = async_def_name(1, 'hello')
    coroutines = [coroutine0, coroutine1]
    event_loop = asyncio.get_event_loop()
    event_loop.run_until_complete()

    event_loop.run_until_complete(asyncio.wait(coroutines))
    event_loop.close()
    pass


def asyncio_py37():
    """Python 3.7+"""
    # asyncio.run(coroutine_name(1, 'main'))
    # asyncio.run(coroutine_main())
    # asyncio.run(coroutine_task())

    pass


async def delay_task(param: str, ):
    delay: float = random.random() * 10
    logger.info(f'param:{param}, delay:{delay}, task start.')
    await asyncio.sleep(delay)
    logger.info(f'param:{param}, delay:{delay}, task end.')


async def run_task():
    futures = list()
    for i in range(10):
        future = asyncio.create_task(delay_task(f'task-{i}'))
        futures.append(future)

    await asyncio.gather(*futures)


def run_main():
    asyncio.run(run_task())


if __name__ == '__main__':
    logger.info('start')

    # asyncio_py36()

    # asyncio.gather()
    # asyncio.shield()
    run_main()
    logger.info('end')

    # 统计函数执行时间
    # t = timeit(stmt='main()', setup='from __main__ import main', number=1)
    # logger.info(t)
    pass
